package bb.lanxing.util;

import com.github.mikephil.charting.utils.Utils;

public class DoubleBuffer {
    private final double[] buffer;
    private int index;
    private boolean isFull;

    public DoubleBuffer(int i) {
        if (i < 1) {
            throw new IllegalArgumentException("The buffer size must be greater than 1.");
        }
        this.buffer = new double[i];
        reset();
    }

    public void reset() {
        this.index = 0;
        this.isFull = false;
    }

    public boolean isFull() {
        return this.isFull;
    }

    public double getAverage() {
        int length = this.isFull ? this.buffer.length : this.index;
        double d = Utils.DOUBLE_EPSILON;
        if (length == 0) {
            return Utils.DOUBLE_EPSILON;
        }
        for (int i = 0; i < length; i++) {
            d += this.buffer[i];
        }
        return d / length;
    }

    public double[] getAverageAndVariance() {
        int length = this.isFull ? this.buffer.length : this.index;
        if (length == 0) {
            return new double[]{Utils.DOUBLE_EPSILON, Utils.DOUBLE_EPSILON};
        }
        double d = Utils.DOUBLE_EPSILON;
        double d2 = 0.0d;
        for (int i = 0; i < length; i++) {
            double[] dArr = this.buffer;
            d += dArr[i];
            d2 += Math.pow(dArr[i], 2.0d);
        }
        double d3 = length;
        double d4 = d / d3;
        return new double[]{d4, (d2 / d3) - Math.pow(d4, 2.0d)};
    }

    public void setNext(double d) {
        int i = this.index;
        double[] dArr = this.buffer;
        if (i == dArr.length) {
            this.index = 0;
        }
        int i2 = this.index;
        dArr[i2] = d;
        int i3 = i2 + 1;
        this.index = i3;
        if (i3 == dArr.length) {
            this.isFull = true;
        }
    }

    public String toString() {
        StringBuffer stringBuffer = new StringBuffer("Full: ");
        stringBuffer.append(this.isFull);
        stringBuffer.append("\n");
        int i = 0;
        while (i < this.buffer.length) {
            stringBuffer.append(i == this.index ? "<<" : "[");
            stringBuffer.append(this.buffer[i]);
            stringBuffer.append(i == this.index ? ">> " : "] ");
            i++;
        }
        return stringBuffer.toString();
    }
}
